from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from datetime import datetime as dt
import datetime
from google.appengine.api import users
from models.ChiTieuKinhDoanh import ChiTieuKinhDoanh
import WSGI
import json as simplejson
import logging
import math
import webapp2

logger = logging.getLogger("GUIChiTieuKinhDoanh")

class GUIHomePage(webapp2.RequestHandler):
    def get(self):
        template_values = {
                        'nickname': 'Nguyen Minh Hung',
                        'signOutUrl': users.create_logout_url(self.request.uri)
        }

        template = WSGI.jinja_environment.get_template('/html/Home.html')
        self.response.out.write(template.render(template_values))


class JsonRequestHandler(webapp2.RequestHandler):
    def get(self):
        funcName = self.request.get('func')
        funcMapping = {'getListChiTieuKinhDoanh': 'getListChiTieuKinhDoanh',
                       'updateChiTieuKinhDoanh': 'updateChiTieuKinhDoanh'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    def post(self):
        return self.get()
    
    def getListChiTieuKinhDoanh(self):
        gridRowNum = int(self.request.get('rows'))
        pageNum = int(self.request.get('page'))
        maNV = self.request.get('maNV')
        thang = self.request.get('thang')
        nam = self.request.get('nam')
        rows, rowNum = DaoQuanLyNhanVien.getListChiTieuKinhDoanh(maNV, thang, nam, gridRowNum, int((pageNum-1)*gridRowNum))
        results = {'page': pageNum, 'total': math.ceil(float(rowNum)/gridRowNum), 'records':rowNum, 'rows':rows}
        return simplejson.dumps(results)
    
    def updateChiTieuKinhDoanh(self):
        now = dt.now() + datetime.timedelta(hours=7)
        if id != '_empty':
            ctkd = ChiTieuKinhDoanh.get_by_id(int(id))
        else:
            ctkd = ChiTieuKinhDoanh()
        oper = self.request.get('oper')
        logger.debug(oper)
        if oper == 'del':
            if ctkd.nam <= now.year and ctkd.thang < now.month:
                return 0
            DaoQuanLyNhanVien.deleteChiTieuKinhDoanh(ctkd)
            return 1
        else:
            thang = int(self.request.get('thang'))
            nam = int(self.request.get('nam'))
            if nam <= now.year and thang < now.month:
                return 0
            ctkd.maNV = int(self.request.get('tenNV'))
            ctkd.tenNV = DaoQuanLyNhanVien.getNhanVienById(ctkd.maNV).tenNV
            ctkd.thang = thang
            ctkd.nam = nam
            ctkd.doanhSo = int(self.request.get('doanhSo'))
            
            DaoQuanLyNhanVien.createOrUpdateChiTieuKinhDoanh(ctkd)
            return 1
        
        
            
        